package jhc.cn.moviegallery;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.SystemClock;
import android.util.Log;

import java.util.List;

/**
 * Created by luyanfei on 16-11-30.
 */

public class PollService extends IntentService {
    private static final String TAG = PollService.class.getName();

    public PollService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if(!isNetworkAvaiableAndConnected()) {
            return;
        }
        Log.d(TAG, "polling service started: " + intent);
        String lastTitlesDigest = QueryPreferences.getStoredTitlesDigest(this);
        List<GalleryItem> latestTheaterItems = new DoubanFetchr().fetchInTheaters();
        String newTitlesDigest = QueryPreferences.computeMd5(latestTheaterItems);
        if(!newTitlesDigest.equals(lastTitlesDigest)) {
            QueryPreferences.setStoredTitlesDigest(this, latestTheaterItems);
        }
    }

    //Android为用户提供了关闭后台应用网络连接的功能。对于非常耗电的应用而言,这项功能可极大地改善手机的续航。
    //然而,这也意味着在后台连接网络时,需使用 ConnectivityManager 确认网络连接是否可用。
    private boolean isNetworkAvaiableAndConnected() {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        return manager.getActiveNetworkInfo() != null && manager.getActiveNetworkInfo().isConnected();
    }

    public static Intent newIntent(Context context) {
        return new Intent(context, PollService.class);
    }

    public static void setServiceAlarm(Context context, boolean isOn) {
        Intent intent = PollService.newIntent(context);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        if(isOn) {
            alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
                    AlarmManager.INTERVAL_HOUR, pendingIntent);
        } else {
            alarmManager.cancel(pendingIntent);
            pendingIntent.cancel();
        }
    }

    /**
     * 撤销定时器也随即撤消了 PendingIntent ,可通过检查 PendingIntent 是否存在来确认
     * 定 时 器 激 活 与 否 。 具 体 代 码 实 现 时 , 传 入 PendingIntent.FLAG_NO_CREATE 标 志 给
     * PendingIntent.getService(...) 方法即可。该标志表示如果 PendingIntent 不存在,则返回null ,而不是创建它。
     * @param context
     * @return
     */
    public static boolean isServiceAlarmOn(Context context) {
        Intent intent = PollService.newIntent(context);
        PendingIntent pi = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_NO_CREATE);
        return pi != null;
    }
}
